package main

import (
	"fmt"
	"net/http"
)

// 1. panic-1
func myRequest() string {
	request, _ := http.NewRequest(http.MethodGet, "http://www.imooc.com", nil)
	// 设置请求头
	request.Header.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1")
	// 发起请求
	resp, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	return "request done!"
}

// 2. panic-2
func myRequestPanic(num1, num2 int) int {
	defer func() {
		err := recover()
		if err != nil {
			panic(err)
		}
	}()
	divmod := num1 / num2
	fmt.Println("divmodRes:", divmod)
	return divmod
}

// 3. 使用defer + recover捕获异常
func deferRecover(num1, num2 int) {
	defer func() {
		err := recover()
		if err != nil {
			fmt.Println("capture owner error:", err)
		}
	}()
	fmt.Println("res:", num1/num2)
}

func main() {
	requestRes := myRequest()
	myRequestPanicRes := myRequestPanic(10, 0)
	fmt.Println("requestRes:", requestRes)               // requestRes: request done!
	fmt.Println("myRequestPanicRes:", myRequestPanicRes) // panic ...
	deferRecover(10, 0)                                  // capture owner error: runtime error: integer divide by zero
}
